package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.SensitiveDto;
import com.heima.media.entity.WmSensitive;
import com.heima.media.mapper.WmSensitiveMapper;
import com.heima.media.service.IWmSensitiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import okhttp3.internal.tls.OkHostnameVerifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 敏感词信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-14
 */
@Service
public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements IWmSensitiveService {

    @Override
    public ResponseResult listByPage(SensitiveDto dto) {
        //构建条件
        LambdaQueryWrapper<WmSensitive> query = new LambdaQueryWrapper<>();
        //如果条件不为空按照敏感词名称模糊查询
        if (!StringUtils.isEmpty(dto.getName())){
            query.like(WmSensitive::getSensitives,dto.getName());
        }
        //按照创建时间倒序查询
        query.orderByDesc(WmSensitive::getCreatedTime);
        //构建分页条件
        IPage<WmSensitive> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmSensitive> iPage = this.page(page, query);
        // 构建通用的分页响应
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),iPage.getRecords());
        return result;
    }

    //新增敏感词
    @Override
    public ResponseResult newSave(WmSensitive wmSensitive) {
        //构建条件
        LambdaQueryWrapper<WmSensitive> query = new LambdaQueryWrapper<>();
        query.eq(WmSensitive::getSensitives,wmSensitive.getSensitives());
        int count = this.count(query);
        //如果数据库中有数据，返回友好提示
        if (count > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //没有，新增
        wmSensitive.setCreatedTime(new Date());
        this.save(wmSensitive);
        return ResponseResult.okResult();
    }

    //修改敏感词
    @Override
    public ResponseResult updateSensitive(WmSensitive wmSensitive) {
        //构建条件
        LambdaQueryWrapper<WmSensitive> query = new LambdaQueryWrapper<>();
        query.eq(WmSensitive::getSensitives,wmSensitive.getSensitives());
        int count = this.count(query);
        if (count > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        this.updateById(wmSensitive);
        return ResponseResult.okResult();
    }

    //敏感词删除
    @Override
    public ResponseResult delete(Integer id) {
        this.removeById(id);
        return ResponseResult.okResult();
    }


}
